"""
setting_manage.py
By IT小强xqitw.cn <mail@xqitw.cn>
At 6/16/21 5:01 PM
"""
from os.path import join, isfile
from json import loads, dumps

from .utils import create_settings_path


class SettingsManage:
    """
    配置操作类，获取、保存配置
    """
    __wsl_vbs = r'''If WScript.Arguments.Count <= 0 Then
    WScript.Quit
End If

bat = Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) & WScript.Arguments(0) & ".bat"
arg = ""

If WScript.Arguments.Count > 1 Then
    arg = WScript.Arguments(1)
End If

CreateObject("WScript.Shell").Run """" & bat & """ """ & arg & """", 0, False
'''
    # 默认配置数据
    __settings = {
        'windows_command_encoding': 'gbk',
        'windows_command_power_shell': 'PowerShell.exe',
        'windows_command_bash_exe': 'bash.exe',

        'auto_start_wsl': False,
        'start_show_ui': True,
        'fire_wall_open': False,
        'fire_wall_close': False,
        'wsl_port_text': '',
        'wsl_bat_content': r"""@echo off
wsl.exe -u root"""
    }

    def __init__(self):
        """
        初始化
        """
        self.settings_dir = create_settings_path()
        self.wsl_vbs_path = join(self.settings_dir, 'wsl.vbs')
        self.wsl_bat_path = join(self.settings_dir, 'wsl.bat')
        self.settings_file = join(self.settings_dir, 'settings.json')
        if not isfile(self.settings_file):
            self.__save_file_content()
        self.__settings = {**self.__settings, **self.__get_file_content()}

    def set(self, name, value):
        """
        设置配置
        @param name: 配置名称
        @param value: 配置值
        """
        self.__settings[name] = value
        self.__save_file_content(dumps(self.__settings))

    def get(self, name=None, default_value=None):
        """
        获取配置
        :param name: 配置名称
        :param default_value: 默认值
        :return:
        """
        settings = self.__settings
        if not name:
            return settings
        return settings.get(name, default_value)

    def __get_file_content(self):
        """
        读取json文件的内容并转为字典
        """
        with open(self.settings_file, 'r', encoding='utf8') as f:
            content = f.read()
        settings = loads(content)
        with open(self.wsl_bat_path, 'r', encoding='utf8')as f:
            settings['wsl_bat_content'] = f.read()
        return settings

    def __save_file_content(self, content=None):
        """
        保存配置到json文件
        """
        if content is None:
            content = dumps(self.__settings)
        if not isfile(self.wsl_vbs_path):
            with open(self.wsl_vbs_path, 'w', encoding='utf8')as f:
                f.write(self.__wsl_vbs)
        with open(self.wsl_bat_path, 'w', encoding='utf8')as f:
            f.write(self.__settings.get('wsl_bat_content'))
        with open(self.settings_file, 'w', encoding='utf8') as f:
            return f.write(content) > 0


setting_manage = SettingsManage()
